package com.nsgf.library.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.zhht.htzx.R;
import com.nsgf.library.data.bean.CartItem;
import com.nsgf.library.data.bean.Shop;
import com.zhht.htzx.databinding.ItemCartBinding;

import java.util.List;

public class CartAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_SHOP = 0;
    private static final int TYPE_ITEM = 1;

    private List<Shop.ValidListBean> shops;
    private Context context;
    private OnCartItemChangeListener listener;
    private boolean isUpdating = false;

    public interface OnCartItemChangeListener {
        void onShopSelectedChanged(int shopPosition, boolean isSelected);
        void onItemSelectedChanged(int shopPosition, int itemPosition, boolean isSelected);
        void onQuantityChanged(int shopPosition, Shop.ValidListBean.SpecificationsBean itemPosition, int quantity);
        void onItemRemoved(int shopPosition, int itemPosition);
    }

    public CartAdapter(Context context, List<Shop.ValidListBean> shops, OnCartItemChangeListener listener) {
        this.context = context;
        this.shops = shops;
        this.listener = listener;
    }

    public List<Shop.ValidListBean> getShops() {
        return shops;
    }

    @Override
    public int getItemViewType(int position) {
        int count = 0;
        for (Shop.ValidListBean shop : shops) {
            if (position == count) {
                return TYPE_SHOP;
            }
            count += 1 + shop.getSpecifications().size();
        }
        return TYPE_ITEM;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == TYPE_SHOP) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_shop_header, parent, false);
            return new ShopViewHolder(view);
        } else {
            View view = LayoutInflater.from(context).inflate(R.layout.item_cart, parent, false);
            return new CartViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ShopViewHolder) {
            ((ShopViewHolder) holder).bind(getShopByPosition(position));
        } else if (holder instanceof CartViewHolder) {
            Shop.ValidListBean.SpecificationsBean item = getItemByPosition(position);
            ((CartViewHolder) holder).bind(item, getShopPositionByItemPosition(position));
        }
    }

    @Override
    public int getItemCount() {
        int count = 0;
        for (Shop.ValidListBean shop : shops) {
            count += 1 + shop.getSpecifications().size();
        }
        return count;
    }

    private Shop.ValidListBean getShopByPosition(int position) {
        int count = 0;
        for (Shop.ValidListBean shop : shops) {
            if (position == count) {
                return shop;
            }
            count += 1 + shop.getSpecifications().size();
        }
        return null;
    }

    private Shop.ValidListBean.SpecificationsBean getItemByPosition(int position) {
        int count = 0;
        for (Shop.ValidListBean shop : shops) {
            count++;
            if (position < count + shop.getSpecifications().size()) {
                return shop.getSpecifications().get(position - count);
            }
            count += shop.getSpecifications().size();
        }
        return null;
    }

    private int getShopPositionByItemPosition(int position) {
        int count = 0;
        for (int i = 0; i < shops.size(); i++) {
            if (position < count + 1 + shops.get(i).getSpecifications().size()) {
                return i;
            }
            count += 1 + shops.get(i).getSpecifications().size();
        }
        return -1;
    }

    public void updateData(List<Shop.ValidListBean> newShops) {
        if (isUpdating) return;
        isUpdating = true;
        this.shops = newShops;
        notifyDataSetChanged();
        isUpdating = false;
    }

    public void selectAll(boolean isSelected) {
        if (isUpdating) return;
        isUpdating = true;
        for (Shop.ValidListBean shop : shops) {
            shop.selectAllItems(isSelected);
        }
        notifyDataSetChanged();
        isUpdating = false;
    }


    public double getTotalPrice() {
        double total = 0;
        for (Shop.ValidListBean shop : shops) {
            total += shop.getTotalPrice();
        }
        return total;
    }

    public int getSelectedCount() {
        int count = 0;
        for (Shop.ValidListBean shop : shops) {
            count += shop.getSelectedCount();
        }
        return count;
    }

    class ShopViewHolder extends RecyclerView.ViewHolder {
        private CheckBox checkBox;
        private TextView shopName;

        public ShopViewHolder(@NonNull View itemView) {
            super(itemView);
            checkBox = itemView.findViewById(R.id.checkbox_shop);
            shopName = itemView.findViewById(R.id.shop_name);
        }

        public void bind(Shop.ValidListBean shop) {
            if (shop == null) return;

            shopName.setText(shop.getTenantName());
            // 移除之前的监听器，避免重复触发
            checkBox.setOnCheckedChangeListener(null);
            checkBox.setChecked(shop.isSelected());

            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isUpdating) return;
                isUpdating = true;
                shop.selectAllItems(isChecked);
                if (listener != null) {
                    listener.onShopSelectedChanged(getAdapterPosition(), isChecked);
                }
                // 通知所有商品项更新
                int startPosition = getAdapterPosition() + 1;
                int itemCount = shop.getSpecifications().size();
                notifyItemRangeChanged(startPosition, itemCount);
                isUpdating = false;
            });
        }
    }

    class CartViewHolder extends RecyclerView.ViewHolder {
        private ItemCartBinding itemCartBinding;

        public CartViewHolder(@NonNull View itemView) {
            super(itemView);
            itemCartBinding = DataBindingUtil.bind(itemView);
        }

        public void bind(Shop.ValidListBean.SpecificationsBean item, int shopPosition) {
            if (item == null) return;
            itemCartBinding.setVm(item);
            // 移除之前的监听器，避免重复触发
            itemCartBinding.checkboxItem.setOnCheckedChangeListener(null);
            itemCartBinding.checkboxItem.setChecked(item.isSelected());

            itemCartBinding.checkboxItem.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (isUpdating) return;
                isUpdating = true;
                item.setSelected(isChecked);
                if (listener != null) {
                    listener.onItemSelectedChanged(shopPosition, getAdapterPosition(), isChecked);
                }
                // 更新店铺选中状态
                Shop.ValidListBean shop = shops.get(shopPosition);
                shop.updateShopSelection();
                // 只更新店铺头部
                notifyItemChanged(shopPosition);
                isUpdating = false;
            });

            itemCartBinding.btnMinus.setOnClickListener(v -> {
                if (isUpdating) return;
                if (item.getCount() > 1) {
                    isUpdating = true;
                    item.setCount(item.getCount() - 1);
                    itemCartBinding.quantityText.setText(String.valueOf(item.getCount()));
                    if (listener != null) {
                        listener.onQuantityChanged(shopPosition, item, item.getCount());
                    }
                    isUpdating = false;
                }
            });

            itemCartBinding.btnPlus.setOnClickListener(v -> {
                if (isUpdating) return;
                isUpdating = true;
                item.setCount(item.getCount() + 1);
                itemCartBinding.quantityText.setText(String.valueOf(item.getCount()));
                if (listener != null) {
                    listener.onQuantityChanged(shopPosition,item, item.getCount());
                }
                isUpdating = false;
            });

        }
    }
}